package springmvc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import springmvc.bean.Homework;
import springmvc.bean.Student;
import springmvc.dao.StudentHomeworkJdbc;
import springmvc.service.DbService;
import springmvc.service.impl.DbServiceImpl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class Login_controller {

    ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");

    @RequestMapping("/login")
    public String velidate(Student student, HttpServletRequest req, HttpServletResponse resp) {
        DbServiceImpl dbService = (DbServiceImpl) ac.getBean("DbServiceImpl");
        if ("get".equalsIgnoreCase(req.getMethod())) {
            return "login";
        } else {
            String account = student.getId()+"";
            String password = student.getPassword();
            System.out.println("login servlet:  " + account + "    "+ password);
            if(account.equals("1111") && password.equals("1111")){
                System.out.println("教师登录成功:  " + account + "  " + password);
                Cookie cookie = new Cookie("account", account);
                resp.addCookie(cookie);
                return "teacher_index";
            }
            else if(!account.equals("1111")){
                String result = dbService.getPassword(account);
                if(password.equals(result)){
                    System.out.println("登录成功:  "+ account+"   "+password );
                    Cookie cookie = new Cookie("account", account);
                    resp.addCookie(cookie);
                    List<Homework> list = dbService.get_student_homework(account);
                    req.setAttribute("list", list);
                    return "index";
                }
                else {
                    System.out.println("学生登录失败");
                    return "login";
                }
            }
            else{
                System.out.println("教师登录失败");
                return "login";
            }
        }
    }
}
